﻿using BLL;
using Model;
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Thksoft.MXReport
{
    public partial class Yx_DayInterestReport : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.hidCompanyId.Value = CurrentUserCompanyID.ToString(); //当前登陆人公司

                //显示年份
                int year = DateTime.Now.Year;
                for (int i = year; i >= 1900; i--)
                {
                    ddlYear.Items.Add(new ListItem(i.ToString()));
                }
                ddlYear.SelectedValue = year.ToString();

                //显示季度
                DateTime time = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));

                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-3-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                }
                else if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-9-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                }
                else if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-9-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-12-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                }
                else
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                    ListItem item3 = new ListItem("第四季", "9.21-12.20");
                    ddlNum.Items.Add(item3);
                }
            }
        }

        /// <summary>
        /// 查询日利息明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            if (this.hidCompanyId.Value.ToString() == "")
            {
                MessageBox.Show(Page, "【温馨提示】请选择公司");
                return;
            }
            BindDt();
        }

        /// <summary>
        /// 查询数据明细
        /// </summary>
        /// <returns></returns>
        public DataTable BindDt()
        {
            string condition = "";
            string year = ddlYear.SelectedValue.ToString();
            string month = ddlNum.SelectedValue.ToString().Split('-')[0].ToString().Replace('.', '-');
            string eMonth = ddlNum.SelectedValue.ToString().Split('-')[1].ToString().Replace('.', '-');
            string start = "";
            if (month == "12-21")
            {
                string y = Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-1-1").AddYears(-1).ToString().Split('-')[0].ToString();
                start = y + "-" + month;
            }
            else
            {
                start = year + "-" + month;
            }
            string end = year + "-" + eMonth;

            condition += " and trunc(d.bdate) between to_date('" + start + "','yyyy-MM-dd') and to_date('" + end + "','yyyy-MM-dd')";

            if (this.hidCompanyId.Value != "")
            {
                condition += "  and d.companyid in( " + this.hidCompanyId.Value.ToString() + ") ";
            }

            //打印传值
            this.printargs.Value = condition;

            DataTable dt = new Yx_DayInterestBLL().SelectByCon(condition);
            gvUrgent.DataSource = dt;
            gvUrgent.DataBind();
            return dt;
        }

        #region 分页相关

        protected void gvUrgent_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvUrgent.PageIndex = e.NewPageIndex;

                BindDt();

                TextBox tb = (TextBox)gvUrgent.BottomPagerRow.FindControl("inPageNum");
                tb.Text = (gvUrgent.PageIndex + 1).ToString();
            }
            catch { }
        }

        protected void gvUrgent_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "go")
                {
                    TextBox tb = (TextBox)this.gvUrgent.BottomPagerRow.FindControl("inPageNum");
                    int num = Int32.Parse(tb.Text);
                    GridViewPageEventArgs ea = new GridViewPageEventArgs(num - 1);
                    gvUrgent_PageIndexChanging(null, ea);
                }
            }
            catch (Exception)
            {
            }
        }

        #endregion 分页相关

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUrgent_PreRender(object sender, EventArgs e)
        {
            for (int rowIndex = gvUrgent.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow row = gvUrgent.Rows[rowIndex];
                GridViewRow previousRow = gvUrgent.Rows[rowIndex + 1];
                if (row.Cells[0].Text == previousRow.Cells[0].Text)
                {
                    row.Cells[0].RowSpan = previousRow.Cells[0].RowSpan < 2 ? 2 : previousRow.Cells[0].RowSpan + 1;
                    previousRow.Cells[0].Visible = false;
                }
            }
        }

        #region 导出

        /// <summary>
        /// 导出方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOutput_Click(object sender, EventArgs e)
        {
            string fileName = "日利息明细_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string str = "导出人：" + CurrentUserName + " &nbsp;&nbsp;&nbsp;导出时间：" + DateTime.Now;
            lblTJ.Text = str;
            string Types = "UTF-8";
            if (gvUrgent.Rows.Count < 1)
            {
                Types = "gb2312";
            }
            ExportExcel(pnl, fileName, Types);
        }

        /// <summary>
        /// 导出方法
        /// </summary>
        /// <param name="objControl"></param>
        /// <param name="strFileName"></param>
        public void ExportExcel(System.Web.UI.WebControls.WebControl objControl, string strFileName, string Types)
        {
            strFileName = System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8);
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = Types;
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName + ".xls");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(Types);//gb2312
            System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";

            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            objControl.RenderControl(oHtmlTextWriter);

            objControl = null;
            System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString().Replace("<td", "<td STYLE='MSO-NUMBER-FORMAT:\\@'"));
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }

        #endregion 导出

        protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlYear.SelectedValue.ToString() != DateTime.Now.Year.ToString())
            {
                ddlNum.Items.Clear();
                ListItem item = new ListItem("第一季", "12.21-3.20");
                ddlNum.Items.Add(item);
                ListItem item1 = new ListItem("第二季", "3.21-6.20");
                ddlNum.Items.Add(item1);
                ListItem item2 = new ListItem("第三季", "6.21-9.20");
                ddlNum.Items.Add(item2);
                ListItem item3 = new ListItem("第四季", "9.21-12.20");
                ddlNum.Items.Add(item3);
            }
            else
            {
                ddlNum.Items.Clear();
                DateTime time = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-12-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-3-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                    ListItem item3 = new ListItem("第四季", "");
                    ddlNum.Items.Add(item3);
                }
                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-3-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                }
                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-9-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                }
                else
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                }
            }
        }

        protected void gvUrgent_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "cssd=this.style.backgroundColor;this.style.backgroundColor='#d5e7ff'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=cssd");
            }
        }

        /// <summary>
        /// 当前用户所属公司ID
        /// </summary>
        public static int CurrentUserCompanyID
        {
            get
            {
                object companyId = null;
                companyId = (HttpContext.Current.Session["SysUserInfo"] as Sys_User).USER_COMPANY;
                if (companyId != null)
                {
                    return Convert.ToInt32(companyId.ToString().Trim());
                }
                else
                {
                    throw new NullReferenceException("对不起，您的登录已过期！请重新登录。");
                }
            }
        }

        ///<summary>
        /// 当前用户姓名
        ///</summary>
        public static string CurrentUserName
        {
            get
            {
                object CurrentUserName = (HttpContext.Current.Session["SysUserInfo"] as Sys_User).USER_NAME;
                if (CurrentUserName != null)
                {
                    return CurrentUserName.ToString();
                }
                else
                {
                    throw new NullReferenceException("对不起，您的登录已过期！请重新登录。");
                }
            }
        }

        /// <summary>
        /// GridView标题列排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUrgent_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["SortOrder"] == null ? null : (string)ViewState["SortOrder"];
            OrderDire = ViewState["OrderDire"] == null ? null : (string)ViewState["OrderDire"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "Desc")
                    OrderDire = "ASC";
                else
                    OrderDire = "Desc";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["SortOrder"] = SortOrder;
            ViewState["OrderDire"] = OrderDire;
            BindProjectName(true);
        }

        /// <summary>
        /// 绑定项目名称（非动态）绑定GridView
        /// </summary>
        public void BindProjectName(bool iSsort)
        {
            string condition = "";
            string year = ddlYear.SelectedValue.ToString();
            string month = ddlNum.SelectedValue.ToString().Split('-')[0].ToString().Replace('.', '-');
            string eMonth = ddlNum.SelectedValue.ToString().Split('-')[1].ToString().Replace('.', '-');
            string start = "";
            if (month == "12-21")
            {
                string y = Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-1-1").AddYears(-1).ToString().Split('-')[0].ToString();
                start = y + "-" + month;
            }
            else
            {
                start = year + "-" + month;
            }
            string end = year + "-" + eMonth;

            condition += " and trunc(d.bdate) between to_date('" + start + "','yyyy-MM-dd') and to_date('" + end + "','yyyy-MM-dd')";

            if (this.hidCompanyId.Value != "")
            {
                condition += "  and d.companyid in( " + this.hidCompanyId.Value.ToString() + ") ";
            }

            //打印传值
            this.printargs.Value = condition;

            DataTable dt = new Yx_DayInterestBLL().SelectByCon(condition);

            DataView view = dt.DefaultView;
            if (iSsort)
            {
                string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
                view.Sort = sort;//设置排序
            }

            gvUrgent.DataSource = view;

            gvUrgent.DataBind();
        }
    }
}